//
//  ZoneAlertsViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/3/22.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "ZoneAlertsViewController.h"
#import "NetworkCommand.h"
#import "UserModel.h"
#import "ZoneAlertTableViewCell.h"
#import "NewZoneViewController.h"
#import "TotalDeviceSelectedViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <MJRefresh.h>
#import <SVProgressHUD.h>

/* 弧度转角度 */
#define SK_RADIANS_TO_DEGREES(radian) \ ((radian) * (180.0 / M_PI))
/* 角度转弧度 */
#define SK_DEGREES_TO_RADIANS(angle) \ ((angle) / 180.0 * M_PI)

typedef NS_ENUM(NSInteger,ZoneType){
    
    ZoneTypeGeneric = 0,
    ZoneTypeSafeFence,
    ZoneTypeOneTime,
    ZoneTypeDonger
    
};

@interface ZoneAlertsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UserModel *userModel;
@property (strong, nonatomic) NSArray *zoneAlertArray;
@property (strong, nonatomic) NSArray *lastStatusDataArray;

@property (weak, nonatomic) IBOutlet UITableView *zoneAlertTableView;
@property (weak, nonatomic) IBOutlet UILabel *noDataLabel;


@end

@implementation ZoneAlertsViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpView];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
//    [self refreshZoneAlertTableView];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [SVProgressHUD dismiss];
    
}

#pragma mark 初始化
-(void)setUpView{
    
    self.zoneAlertTableView.delegate = self;
    
    self.zoneAlertTableView.dataSource = self;
    
    self.zoneAlertTableView.tableFooterView = [[UIView alloc]init];
    
    self.zoneAlertTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        [self refreshZoneAlertTableView];
        
    }];
    
    [self refreshZoneAlertTableView];
    
}

-(void)refreshZoneAlertTableView{
    
    [SVProgressHUD showWithStatus:@"Loading..."];
    
    [NetworkCommand GetGeoFencesByDeviceForSerialNumber:self.userModel.selectedDeviceSerialNumber Success:^(NSArray *responseObject) {
        
        
        if (!(responseObject.count > 0)) {
            
            [SVProgressHUD showErrorWithStatus:@"No Data"];
            
            [SVProgressHUD dismiss];
            
            [self.zoneAlertTableView reloadData];
            
            [self.zoneAlertTableView.mj_header endRefreshing];
            
        }else{
            
            self.zoneAlertArray = responseObject;
            
            [NetworkCommand getLastStatusDataForSerialNumber:self.userModel.selectedDeviceSerialNumber Success:^(NSArray *responseObject) {
                
                self.lastStatusDataArray = responseObject;
                
                if (responseObject > 0) {
                    
                    [SVProgressHUD dismiss];
                    
                }else{
                    
                    
                    [SVProgressHUD showErrorWithStatus:@"Device not found"];
                    
                    [SVProgressHUD dismissWithDelay:1];
                    
                }
                
                
                
                [self.zoneAlertTableView reloadData];
                
                [self.zoneAlertTableView.mj_header endRefreshing];
                
            } failure:^{
                
                [SVProgressHUD showErrorWithStatus:@"Device not found"];
                
                [SVProgressHUD dismissWithDelay:1];
                
                [self.zoneAlertTableView reloadData];
                
                [self.zoneAlertTableView.mj_header endRefreshing];
                
            }];
            
        }
        
        
        
        
    } failure:^{
        
        [SVProgressHUD showErrorWithStatus:@"Failed"];
        
        [SVProgressHUD dismissWithDelay:1];
        
        self.zoneAlertArray = nil;
        
        [self.zoneAlertTableView reloadData];
        
        [self.zoneAlertTableView.mj_header endRefreshing];
    }];
    
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.zoneAlertArray.count > 0) {
        
        self.noDataLabel.hidden = YES;
        
    }else{
        
        self.noDataLabel.hidden = NO;
        
    }
    
    return self.zoneAlertArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.zoneAlertArray[indexPath.row];
    
    ZoneAlertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZoneAlertTableViewCell"];
    
    if (cell == nil) {
        
        cell = [[ZoneAlertTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ZoneAlertTableViewCell"];
        
        
        
    }
    
    NSString *fenceNameString = [dict valueForKey:NC_FENCE_NAME];
    
    NSString *zoneTypeString;
    
    NSInteger zoneType = [[dict valueForKey:NC_ZONE_TYPE] integerValue];
    
    switch (zoneType) {
        case ZoneTypeGeneric:
            
            zoneTypeString = @"Danger Zone";
            
            break;
            
        case ZoneTypeSafeFence:
            
            zoneTypeString = @"SafeFence Zone";
            
            break;
            
        case ZoneTypeOneTime:
            
            zoneTypeString = @"OneTime Zone";
            
            break;
            
        case ZoneTypeDonger:
            
            zoneTypeString = @"Danger Zone";
            
            break;
            
        default:
            break;
    }
    
    
    //距离
    NSString *pointsString = [dict valueForKey:NC_POINTS];
    
    NSString *distanceString;
    
    NSNumber *distanceNumber = [self getDistanceForPointsString:pointsString];
    
    if (distanceNumber) {
        
        distanceString = [NSString stringWithFormat:@"%@m",distanceNumber];
        
    }else{
        
        distanceString = @"Device not found";
        
    }
    
    
    
    
    
    
    
    [cell setUpFenceName:fenceNameString zoneType:zoneTypeString distance:distanceString responseObjectDictionary:dict];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 104;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"ZoneAlertsViewController" bundle:[NSBundle mainBundle]];
    
    NewZoneViewController *newZoneViewController = [storyboard instantiateViewControllerWithIdentifier:@"NewZoneViewController"];
    
    NSDictionary *dict = self.zoneAlertArray[indexPath.row];
    
    newZoneViewController.fenceDictionary = dict;
    
    [self showViewController:newZoneViewController sender:nil];
    
    
}

#pragma mark 获取距离
-(NSNumber *)getDistanceForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        //半径
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        NSArray *linePointArray = [[pointArray lastObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        double lineLatitude = [[linePointArray firstObject] doubleValue];
        
        double lineLongitude = [[linePointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f_%f,%f",centerLatitude,centerLongitude,lineLatitude,lineLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];
        
        CLLocation *lineLocation = [[CLLocation alloc]initWithLatitude:lineLatitude longitude:lineLongitude];
        
        int radius = [centerLocation distanceFromLocation:lineLocation];
        
        NSLog(@"radius %d",radius);
        
        if (self.lastStatusDataArray.count > 0) {
            
            NSDictionary *deviceDict = [self.lastStatusDataArray firstObject];
            
            double deviceLatitude = [[deviceDict valueForKey:NC_LAT] doubleValue];
            
            double deviceLongitude = [[deviceDict valueForKey:NC_LNG] doubleValue];
            
            CLLocation *deviceLocation = [[CLLocation alloc]initWithLatitude:deviceLatitude longitude:deviceLongitude];
            
            int deviceRadius = [centerLocation distanceFromLocation:deviceLocation];
            
            int distance = deviceRadius - radius;
            
            if (distance > 0) {
                
                return @(distance);
                
            }else{
                
                return @(0);
                
            }
            
        }
        
    }
    
    return nil;
    
}

#pragma mark 获取半径
-(NSNumber *)getRadiusForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        NSArray *linePointArray = [[pointArray lastObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        double lineLatitude = [[linePointArray firstObject] doubleValue];
        
        double lineLongitude = [[linePointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f_%f,%f",centerLatitude,centerLongitude,lineLatitude,lineLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];
        
        CLLocation *lineLocation = [[CLLocation alloc]initWithLatitude:lineLatitude longitude:lineLongitude];
        
        int radius = [centerLocation distanceFromLocation:lineLocation];
        
        NSLog(@"radius %d",radius);
        
        return @(radius);
        
    }

    return nil;
}

#pragma mark 刷新列表
-(void)reloadFenceTableView{
    
    [self refreshZoneAlertTableView];
    
}

#pragma mark RemoveButton
- (IBAction)touchRemoveButton:(id)sender {
    
    for (ZoneAlertTableViewCell *cell in self.zoneAlertTableView.visibleCells) {
        
        [cell deleteButtonHidden];
    }
    
}

#pragma mark 点击列表按钮
- (IBAction)toucTotalDeviceButton:(id)sender {
    
    TotalDeviceSelectedViewController *totalDeviceSelectedViewController = [[TotalDeviceSelectedViewController alloc]init];
    
    [self.navigationController showViewController:totalDeviceSelectedViewController sender:nil];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
